﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone;
using System.Collections.ObjectModel;
using ActivityTracker.Library;
using System.Windows.Navigation;
using Common.Library;



namespace ActivityTracker
{
    public partial class AddNewActivity : PhoneApplicationPage
    {
        #region Global

        Actvity objActivity = new Actvity();
        ActivityData objActivityData = new ActivityData();
        Category objCategory = new Category();
        UserImage objUserImage = new UserImage();
       
        string actId = "";

        #endregion

        #region constructor

        public AddNewActivity()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(AddNewActivity_Loaded);
        }

        void AddNewActivity_Loaded(object sender, RoutedEventArgs e)
        {
            string back;
            back = SettingsHelper.getStringValue("back");
            if (back == "back")
            {
                SetPicture();
                SettingsHelper.Save("back", "");
            }
            
        }

       

        #endregion

        #region page events
       
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               

                if (NavigationContext.QueryString.TryGetValue("actId", out actId))
                {

                    App.actId = actId;
                    ApplicationTitle.Text = "ACTIVITY TRACKER - EDIT ACTIVITY";
                    objActivityData.LoadSelectedActivity(actId);

                }
                else
                {
                    ApplicationTitle.Text = "ACTIVITY TRACKER - NEW ACTIVITY";
                }

                if (App.actName != null) tbxNewActivity.Text = App.actName;
                if (App.AcitivityImgSrc != null)
                    imgActivity.Source = App.AcitivityImgSrc;
               
                cbxLocationTracking.IsChecked = App.LocTrackingStatus;
                lbxCategories.ItemsSource = objCategory.LoadCheckedCategories();
              
            }
            catch (Exception ex)
            {
                string mess = "Exception in PhoneApplicationPage_Loaded Method In AddNewActivity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void AppBarSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (tbxNewActivity.Text != "")
                {
                    if (CommonClass.findSpecialSymbols(tbxNewActivity.Text))
                    {
                        tblkActValidation.Visibility = Visibility.Collapsed;
                        XElement catElement = objActivity.GetCategoryElement(lbxCategories);
                        if (catElement.Elements().Count() > 0)
                        {
                            tblkcatValidation.Visibility = Visibility.Collapsed;

                            string imgName = "";
                            //if (IsolatedSettings.getStringValue("write") == "true")
                            //{
                               // IsolatedSettings.save("write", "");
                                imgName = tbxNewActivity.Text + ".jpg";
                          //  }
                            //else
                            //{
                            //    if (App.ImageBytes != null)
                            //    {
                            //        imgName = tbxNewActivity.Text + ".jpg";
                            //        objUserImage.SaveImage(imgName, "ActivityTracker/ActivityImages", App.ImageBytes);
                            //    }
                            //}

                            if (App.actId != null)
                                objActivity.UpdateActivity(App.actId, catElement, tbxNewActivity.Text.ToString(), imgName, Convert.ToBoolean(cbxLocationTracking.IsChecked));
                            else
                                objActivity.SaveNewActivity(catElement, tbxNewActivity.Text.ToString(), imgName, Convert.ToBoolean(cbxLocationTracking.IsChecked));

                            objActivityData.ActivityOldDataClearing();
                            NavigationService.Navigate(new Uri("/Views/Activities/MyActivities.xaml", UriKind.Relative));
                        }
                        else
                            tblkcatValidation.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        tblkActValidation.Text = "No special chars allowed";
                        tblkActValidation.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    tblkActValidation.Text = "Required";
                    tblkActValidation.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in AppBarSave_Click Method In AddNewActivity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void SelectCategory_Click(object sender, MouseButtonEventArgs e)
        {
            try
            {
                App.actName = tbxNewActivity.Text;
                App.AcitivityImgSrc = imgActivity.Source;
                App.LocTrackingStatus = Convert.ToBoolean(cbxLocationTracking.IsChecked);
                NavigationService.Navigate(new Uri("/Views/Categories/Categories.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                string mess = "Exception in SelectCategory_Click Method In AddNewActivity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void imgActivity_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
           
            PhotoChooserTask phtochoser = new PhotoChooserTask();
           
            phtochoser.Completed += new EventHandler<PhotoResult>(phtochoser_Completed);
            phtochoser.Show();
            
        }

        void phtochoser_Completed(object sender, PhotoResult e)
        {
            App.AcitivityImgSrc = null;
            try
            {
                App.actName = tbxNewActivity.Text;
                if (e.TaskResult == TaskResult.OK)
                {
                    App.ImageBytes = new byte[e.ChosenPhoto.Length];
                    e.ChosenPhoto.Read(App.ImageBytes, 0, App.ImageBytes.Length);
                    e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                    var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                    App.AcitivityImgSrc = imageSource;
                    SettingsHelper.Save("type", "Activity");
                    NavigationService.Navigated += navigationService_Navigated;
            
                   
                   
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in phtochoser_Completed Method In AddNewActivity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }
        void navigationService_Navigated(object sender, NavigationEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Themes/Photo Chooser.xaml",UriKind.RelativeOrAbsolute));
            NavigationService.Navigated -= navigationService_Navigated;
        } 
        private void SetPicture()
        {
            BitmapImage bi = new BitmapImage();
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists("ActivityTracker/ActivityImages/"+ App.actName + ".jpg"))
                {
                    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("ActivityTracker/ActivityImages/" + App.actName + ".jpg", FileMode.Open, FileAccess.Read))
                    {

                        bi.SetSource(fileStream);
                        //App.ImageBytes=new byte[fileStream.Length];
                    }
                }
            }
      
            imgActivity.Source =App.AcitivityImgSrc= bi;
          
           
                     
        }
        private void tbxNewActivity_GotFocus(object sender, RoutedEventArgs e)
        {
            tblkActValidation.Visibility = Visibility.Collapsed;
        }

        private void AppBarHelp_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Help/Help.xaml?id=8&url=FmrGr3JWLeU", UriKind.Relative));
        }

        #endregion
    }
}